<?php

namespace app\api\controller;


use app\admin\model\BillModel;
use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomModel;
use app\common\model\Contract as ContractModel;
use app\common\controller\Api;
use Exception;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;


class Recycle extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    public function stat()
    {
        $user_id = $this->auth->id;
        $building = BuildingModel::onlyTrashed()->where('user_id', $user_id)->count();
        $room = BuildingModel::onlyTrashed()->where('user_id', $user_id)->count();
        $bill = BillModel::onlyTrashed()->where('user_id', $user_id)->count();
        $contract = ContractModel::onlyTrashed()->where('homeowner_id', $user_id)->count();


        $this->success('ok', [
            'building' => $building,
            'room' => $room,
            'bill' => $bill,
            'contract' => $contract
        ]);
    }

    public function building()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $kw = $this->request->param('kw');
        $where = [];
        $where['user_id'] = $this->auth->id;
        if ($kw) {
            $where['address'] = ['like', '%' . $kw . '%'];
        }
        $where += $this->getTimeWhere();
        $list = BuildingModel::onlyTrashed()
            ->with('delUser')
            ->where($where)
            ->field('id,address,delete_time,del_uid')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['delete_time_text'], true);
            });

        $this->success('成功', $list);
    }

    private function getTimeWhere()
    {
        $type = $this->request->param('type');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $where = [];
        if ($type == 1) {// 今天
            $where['delete_time'] = ['between time', ['today', 'today 23:59:59']];
        } elseif ($type == 2) {// 昨天
            $where['delete_time'] = ['between time', ['yesterday', 'yesterday 23:59:59']];
        } elseif ($type == 3) {// 本月
            $where['delete_time'] = ['between time', ['first Day of this month 00:00:00', 'last Day of this month 23:59:59']];
        } elseif ($type == 4) {// 上月
            $where['delete_time'] = ['between time', ['first Day of last month 00:00:00', 'last Day of last month 23:59:59']];
        } elseif ($type == 5) {// 近15天
            $where['delete_time'] = ['between time', ['-15 day 00:00:00', 'today 23:59:59']];
        }

        if ($start && $end) {
            $where['delete_time'] = ['between time', [$start, $end]];
        } elseif ($start) {
            $where['delete_time'] = ['>= time', $start];
        } elseif ($end) {
            $where['delete_time'] = ['<= time', $end];
        }

        return $where;
    }

    /**
     * 还原
     *
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function building_restore()
    {
        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = BuildingModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 真实删除
     *
     * @return void
     */
    public function building_destroy()
    {

        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = BuildingModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }


    public function room()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $build_id = $this->request->param('build_id');
        $kw = $this->request->param('kw');
        $where = [];
        $where['user_id'] = $this->auth->id;
        if ($kw) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }
        if ($build_id) {
            $where['build_id'] = $build_id;
        }
        $where += $this->getTimeWhere();
        $list = BuildingRoomModel::onlyTrashed()
            ->with(['delUser','building' => function ($query) {
                $query->removeOption('soft_delete')->withField('id,address');
            }])
            ->where($where)
            ->field('id,build_id,name,status,price,delete_time,del_uid')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['delete_time_text'], true);
            });

        $this->success('成功', $list);
    }

    /**
     * 还原
     *
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function room_restore()
    {
        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = BuildingRoomModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 真实删除
     *
     * @return void
     */
    public function room_destroy()
    {

        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = BuildingRoomModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }


    public function bill()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $build_id = $this->request->param('build_id');
        $kw = $this->request->param('kw');
        $where = [];
        $where['b.user_id'] = $this->auth->id;
        if ($kw) {
            $where['room_name'] = ['like', '%' . $kw . '%'];
        }
        if ($build_id) {
            $where['build_id'] = $build_id;
        }
        $where += $this->getTimeWhere();

        $list = BillModel::onlyTrashed()->alias('b')
            ->with(['delUser'])
            ->join('user_contract c', 'c.id = b.contract_id', 'left')
            ->where($where)
            ->field('b.id,b.money,b.day,b.status,b.pay_time,category,b.remark,b.delete_time,b.del_uid,b.contract_id,
            c.build_address,c.room_name,c.user_name,c.user_phone')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['delete_time_text'], true);
            });

        $this->success('成功', $list);
    }

    /**
     * 还原
     *
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function bill_restore()
    {
        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = BillModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 真实删除
     *
     * @return void
     */
    public function bill_destroy()
    {

        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = BillModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }


    public function contract()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $kw = $this->request->param('kw');
        $build_id = $this->request->param('build_id');
        $where = [];
        $where['homeowner_id'] = $this->auth->id;
        if ($kw) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }
        if ($build_id) {
            $where['build_id'] = $build_id;
        }
        $where += $this->getTimeWhere();
        $list = ContractModel::onlyTrashed()
            ->with('delUser')
            ->where($where)
            ->field('id,build_address,room_name,money_zu,status,user_name,user_phone,start_time,end_time,deletetime,del_uid')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['delete_time_text'], true);
            });

        $this->success('成功', $list);
    }

    /**
     * 还原
     *
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function contract_restore()
    {
        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = ContractModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 真实删除
     *
     * @return void
     */
    public function contract_destroy()
    {

        $ids = $this->request->param('ids');
        $count = 0;
        Db::startTrans();
        try {
            $list = ContractModel::onlyTrashed()->where('id', 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('成功');
        }
        $this->error('失败');
    }
}
